﻿package{
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.FileFilter;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	
	public class Main extends Sprite{
		
		private var byteArray:ByteArray;
		private var console:TextField;
		private var loader:Loader;
		private var time:int;

		private var _fileUrl:String;

		private var _urlLoader:URLLoader;
		
		public function Main(){
			loader=new Loader();
			print("点击舞台加载一个LZMA压缩过的SWF \n");
			stage.addEventListener(MouseEvent.CLICK,onClick);
		}
		
		public function print(...args):void{
			if(!console){
				console=new TextField();
				console.autoSize="left";
				console.background=true;
				console.defaultTextFormat=new TextFormat("simsun");
				stage.addChild(console);
			}
			for(var i:int=0,n:int=args.length-1;i<=n;i++){
				console.appendText(args[i]+(i==n?"\n":" "));
			}
		}
		
		
		/**
		 *选择输出路径完成 
		 * @param e
		 */		
		private function selectExportPathOK(e:Event):void{
			var file:File = e.target as File;
			file.removeEventListener(Event.SELECT,selectExportPathOK);

			_fileUrl = file.url ;
			_urlLoader = new URLLoader();
			_urlLoader.dataFormat = URLLoaderDataFormat.BINARY ;
			_urlLoader.load( new URLRequest(file.url) )
			_urlLoader.addEventListener( Event.COMPLETE ,onLoaded ) ;
			
		}
		
		
		private function onClick(event:MouseEvent):void{
			
			var file:File = new File();
			file.browseForOpen("选择zws文件",[new FileFilter("SWF File (.swf)","*.swf")]);
			file.addEventListener(Event.SELECT,selectExportPathOK);	
		}
		
		
		private function onLoaded(event:Event):void{
			
			if(_urlLoader.data[0]!=0x5a){
				print("不是LZMA压缩过的SWF ");
				return;
			}
			time=getTimer();
			
//			byteArray = LZMA.decode( _urlLoader.data ) ;
			byteArray=LZMA.decodeSWF(_urlLoader.data);
			
			var path:String = _fileUrl.slice(0,_fileUrl.indexOf(".swf"));
			var file:File = new File( path+"_z.swf");
			var fs:FileStream = new FileStream();
			fs.open(file,FileMode.WRITE);
			fs.writeBytes(byteArray);
			fs.close();
			

		}
		
	}
}
